﻿using BCCommon;
using BCCommon.Enums;
using BCData.Sim.Admin.AdminAuth;
using BCDto.Sim.Admin.AdminAuth;
using BCEntity.Sim.Admin.AdminAuth;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCData.Sim.Admin.Admin;

namespace BCService.Sim.Admin.AdminAuth
{
    public class AdminAuthService : IAdminAuthService
    {
        private readonly IDatabaseContext databaseContext;
        private readonly IRedisService redisService;
        private readonly IAdminAuthData adminAuthData;
        private readonly IAdminData adminData;
        private readonly string key = string.Format("{0}", EntityNameConst.AdminAuthEntity);

        public AdminAuthService(IDatabaseContext databaseContext,
            IRedisService redisService,
            IAdminAuthData adminAuthData,
            IAdminData adminData)
        {
            this.databaseContext = databaseContext;
            this.redisService = redisService;
            this.adminAuthData = adminAuthData;
            this.adminData = adminData;
        }

        #region 检查员工授权信息是否存在
        public bool Exists(long adminAuthId)
        {
            return this.adminAuthData.Exists(adminAuthId).GetAwaiter().GetResult();
        }
        #endregion

        #region 添加员工授权信息
        public AdminAuthDto Add(AdminAuthRequestDto requestDto)
        {
            if (!this.adminData.CheckAdminExists(requestDto.AdminId).Result)
            {
                throw new ArgumentException("此员工信息不存在!");
            }
            if (this.adminAuthData.Exists(requestDto.AuthType, requestDto.UnionId).Result)
            {
                return this.adminAuthData.GetEntity(requestDto.AuthType, requestDto.UnionId).Result.As<AdminAuthDto>();
            }
            
            var entity = requestDto.As<AdminAuthEntity>();
            
            return this.adminAuthData.Add(entity).GetAwaiter().GetResult().As<AdminAuthDto>();
        }
        #endregion

        #region 修改员工授权信息
        public AdminAuthDto Update(AdminAuthPutDto putDto)
        {
            if (!this.Exists(putDto.AdminAuthId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            if (!this.adminData.CheckAdminExists(putDto.AdminId).Result)
            {
                throw new ArgumentException("此员工信息不存在!");
            }
            if (this.adminAuthData.Exists(putDto.AuthType, putDto.UnionId).Result)
            {
                var oldEntity = this.adminAuthData.GetEntity(putDto.AuthType, putDto.UnionId).Result;
                if(oldEntity.AdminId != putDto.AdminId)
                {
                    throw new ArgumentException("此授权信息已绑定其他用户，无法同时绑定多人!");
                }
            }
            var entity = putDto.As<AdminAuthEntity>();
            var result = this.adminAuthData.Update(entity).GetAwaiter().GetResult().As<AdminAuthDto>();
            string cacheKey = this.redisService.GetKey(key, entity.AdminAuthId);
            this.redisService.DeleteAsync(cacheKey);
            return result;
        }
        #endregion

        #region 删除员工授权信息
        public bool Delete(long adminAuthId)
        {
            if (!this.Exists(adminAuthId))
            {
                throw new ArgumentException("此记录不存在!");
            }

            var result = this.adminAuthData.Delete(adminAuthId).GetAwaiter().GetResult();
            string cacheKey = this.redisService.GetKey(key, adminAuthId);
            this.redisService.DeleteAsync(cacheKey);
            return result;
        }
        #endregion

        #region 获取员工授权信息
        public AdminAuthDto Get(long adminAuthId)
        {
            string cacheKey = this.redisService.GetKey(key, adminAuthId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.adminAuthData.GetEntity(adminAuthId).GetAwaiter().GetResult();
                return data;
            }, TimeSpan.FromMinutes(30));
            return result.As<AdminAuthDto>();
        }
        public AdminAuthDto Get(AuthType authType, string unionId)
        {
            string cacheKey = this.redisService.GetKey(key, authType, unionId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.adminAuthData.GetEntity(authType, unionId).GetAwaiter().GetResult();
                return data;
            }, TimeSpan.FromMinutes(30));
            return result.As<AdminAuthDto>();
        }
        #endregion

        #region 获取员工授权信息列表
        public IEnumerable<AdminAuthDto> GetList(long adminId)
        {
            var result = this.redisService.TryGet(key, () =>
            {
                return this.adminAuthData.GetList(adminId).GetAwaiter().GetResult();
            }, TimeSpan.FromMinutes(30));
            return result.As<IEnumerable<AdminAuthDto>>();
        }
        #endregion

        #region 获取员工授权信息分页
        public PageableList<AdminAuthDto> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key, start, end, sortName, ascending, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.adminAuthData.Query(start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
                return new PageableList<AdminAuthDto>
                {
                    Count = data.Item2,
                    Items = data.Item1.As<IEnumerable<AdminAuthDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now
                };
            }, TimeSpan.FromMinutes(30));

            return result;
        }
        #endregion
    }
}